const Koa = require('koa');
const koaStaticCache = require('koa-static-cache');
const KoaRouter = require('koa-router');
const koaBody = require('koa-body');

let users = [
    {
        id: 1,
        username: 'zMouse'
    },
    {
        id:2,
        username: 'DaHai'
    }
]

const server = new Koa();


server.use(koaStaticCache({
    prefix: '/public',
    dir: './public',
    gzip: true,
    dynamic: true
}));

const router = new KoaRouter();

router.get('/users', async (ctx, next) => {

    let lis = users.map(user => {
        return `<li>${user.username}</li>`;
    }).join('');

    // return new Promise((resolve) => {
    //     setTimeout(()=>{
    //         ctx.body = `
    //             <ul>${lis}</ul>
    //         `;
    //         resolve();
    //     }, 3000);
    // })

    // ctx.body = `
    //     <ul>${lis}</ul>
    // `;

    // ctx.body = lis;

    ctx.body = users;
});

function zmouse() {
    return async (ctx, next) => {
        let data = '';
        ctx.req.on('data', (chunk) => {
            data = chunk.toString();
        })

        ctx.req.on('end', () => {
            console.log(ctx.get('content-type'));
            console.log(data);
        })
    }
}

router.post('/login', zmouse(), koaBody({
    multipart: true
}), async (ctx, next) => {

    let {username, password} = ctx.request.body;

    console.log('username', username);
    console.log('password', password);


    if (!username || !password) {
        ctx.throw(400, '参数错误');
    }

    ctx.body = '登录成功';

});

router.post('/avatar', koaBody({
    multipart: true,
    formidable: {
        uploadDir: './public/avatar',
        keepExtensions: true,
        maxFileSize: 10000000000
    }

}), async (ctx, next) => {

    // console.log(ctx.request.files.avatar);
    let path = ctx.request.files.avatar.path;
    let exec = path.split(/(\/|\\)/gi);
    // console.log(exec);

    let avatarName = exec.pop();
    console.log(avatarName);

    ctx.body = {
        message: '上传成功',
        url: `/public/avatar/${avatarName}`
    };
})



server.use(router.routes());


server.listen(8888);
